#@layout()
#define main()
<input type="hidden" class="layui-input" id="orderId" name="purchaseOrder.orderId" value="#(purchaseOrder.order_id??)"/>
<div class="layui-row layui-col-space1 task-row">
	#@colStart("供应商",3)
	<input id="supplierId" type="hidden" class="layui-input" placeHolder="必填" name="purchaseOrder.supplierId" value="#(purchaseOrder.supplier_id??)"/>
	<input id="supplierName" type="text" class="layui-input" placeHolder="必填" name="purchaseOrder.supplierName" value="#(purchaseOrder.supplierName??)"/>
	#@colEnd()
	#@colStart("起单人",3)
	<input id="originator" type="hidden" placeHolder="必填" class="layui-input" name="purchaseOrder.originator" value="#(purchaseOrder.originator??)" />
	<input id="originatorName" type="text" placeHolder="必填" class="layui-input" name="purchaseOrder.originatorName" value="#(purchaseOrder.originatorName??)" />
	#@colEnd()
	#@colStart("开单时间",3)
	<input id="originatTime" type="text" lay-verType='tips' class="layui-input" name="purchaseOrder.originatTime" value="#(purchaseOrder.originat_time??)" />
	#@colEnd()
	#@colStart("计划到货时间",3)
	<input id="planTime" type="text" lay-verType='tips' class="layui-input" name="purchaseOrder.planTime" value="#(purchaseOrder.plan_time??)" />
	#@colEnd()
</div>

<div class="layui-row layui-col-space1 task-row">
	#@colStart("实际到货时间",3)
	<input id="actualTime" type="text" lay-verType='tips' class="layui-input" name="purchaseOrder.actualTime" value="#(purchaseOrder.actual_time??)" />
	#@colEnd()
	#@colStart('结账方式',3)
	<select id="settleWay" name="purchaseOrder.settleWay" class="layui-input" lay-search>
		<option value="">---请选择---</option>
		#for(data:orderSettleWayMap)
		<option value="#(data.key??)" #if(purchaseOrder.settleWay??==data.key) selected="selected" #end>#(data.value??)</option>
		#end
	</select>
	#@colEnd()
	#@colStart("总计金额",3)
	<input id="totalAmount" type="text" lay-verType='tips' class="layui-input" name="purchaseOrder.totalAmount" value="#(purchaseOrder.total_amount??)" />
	#@colEnd()
	#@colStart("是否含发票",3)
	<select id="containBill" name="purchaseOrder.containBill" class="layui-input" lay-search>
		<option value="">---请选择---</option>
		#for(data:orderContainBillMap)
		<option value="#(data.key??)" #if(purchaseOrder.containBill??==data.key) selected="selected" #end>#(data.value??)</option>
		#end
	</select>
	#@colEnd()
</div>

<div class="layui-row layui-col-space1 task-row">
	#@colStart("税率",3)
	<input id="taxRate" type="text" lay-verType='tips' class="layui-input" name="purchaseOrder.taxRate" value="#(purchaseOrder.tax_rate??)" />
	#@colEnd()
	#@colStart('单据状态',3)
	<select id="status" name="purchaseOrder.status" class="layui-input" lay-search>
		<option value="">---请选择---</option>
		#for(data:orderStatusMap)
		<option value="#(data.key??)" #if(purchaseOrder	.status??==data.key) selected="selected" #end>#(data.value??)</option>
		#end
	</select>
	#@colEnd()
	#@colStart("物流单号",3)
	<input id="logisticsNum" type="text" lay-verType='tips' class="layui-input" name="purchaseOrder.taxRate" value="#(purchaseOrder.logistic_num??)" />
	#@colEnd()
	#@colStart("运费",3)
	<input id="carriage" type="text" lay-verType='tips' class="layui-input" name="purchaseOrder.carriage" value="#(purchaseOrder.carriage??)" />
	#@colEnd()
</div>

<div class='layui-row f-index-toolbar'>
	<div class='layui-col-xs12'>
		<div class="layui-btn-group">
			<button id='addRow' class="layui-btn layui-btn-normal layui-btn-sm">
				<i class="layui-icon">&#xe608;</i> 新增一行
			</button>
		</div>
	</div>
</div>

<!-- 表格列表 -->
<div class="layui-row  f-index-toolbar">
	<div class="layui-col-xs12">
		<table id="maingrid" lay-filter="maingrid"></table>
	</div>
</div>

<div class='layui-row f-index-toolbar'>
	<div class='layui-col-xs12'>
		<div class="layui-btn-group">
			<button id='addRow2' class="layui-btn layui-btn-normal layui-btn-sm">
				<i class="layui-icon">&#xe608;</i> 新增一行
			</button>
		</div>
	</div>
</div>

<!-- 表格列表 -->
<div class="layui-row  f-index-toolbar">
	<div class="layui-col-xs12">
		<table id="payDetail" lay-filter="maingrid"></table>
	</div>
</div>


<div class="text-center">
	<button type="button" id="saveBtn" name="btnSave" class="layui-btn" data-type="save"><i class="layui-icon layui-icon-ok-circle"></i>保存</button>
	<button type="reset" name="btnReset" class="layui-btn layui-btn-primary">取消</button>
</div>


<!-- 	每行的操作按钮 -->
<script type="text/html" id="bar_maingrid">
	<a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="delRow">移除</a>
</script>
<!-- 	每行的操作按钮 -->
<script type="text/html" id="bar_payDetail">
	<a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="delRow2">移除</a>
</script>
#end

#define js()
<script>
	$(function(){

		$("#addRow").click(function(){
			var oldData = table.cache['maingrid'];
			console.log(oldData);
			var newRow = {tempId: new Date().valueOf(),detail_id: '', entity_id: null,par_entity: null,unit: '个',amount: 0,price: 0, discount: 0, sum_money: 0};
			oldData.push(newRow);
			table.reload('maingrid',{
				data : oldData
			});
      	});
		$("#addRow2").click(function(){
			var oldData = table.cache['payDetail'];
			console.log(oldData);
			var newRow = {tempId: new Date().valueOf(),detail_id: '', pay_code: null,sum_money: 0,pay_men: null,receive_men: null,trans_time: 0};
			oldData.push(newRow);
			table.reload('payDetail',{
				data : oldData
			});
		});


		$("#saveBtn").click(function(){
			var detailList = table.cache['maingrid'];
			console.log(detailList);
			var payList = table.cache['payDetail'];
			console.log(payList);
			debugger
			var param = {
				supplierId:$('#supplierId').val(),
				originator:$('#originator').val(),
				originatTime:$('#originatTime').val(),
				planTime:$('#planTime').val(),
				actualTime:$('#actualTime').val(),
				settleWay:$('#settleWay').val(),
				totalAmount:$('#totalAmount').val(),
				containBill:$('#containBill').val(),
				taxRate:$('#taxRate').val(),
				logisticsNum:$('#logisticsNum').val(),
				carriage:$('#carriage').val(),
				status:$('#status').val(),
				detailList: JSON.stringify(detailList),
				payList:JSON.stringify(payList)
			}
			console.log(param)
			layer.confirm('确定要提交吗？',{icon: 3, title:'提示'},function(index){
				$.post("#(path)/erp/order/purchase/saveOrder",param,function(feedback) {
					setTimeout('window.location.reload()',500);
					if (feedback.success) {
						layer.close(index);
						var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
						parent.layer.close(index); //再执行关闭
						windows.location.href="#(path)/erp/order/purchase/index";
					} else {
						$(".layui-laypage-btn").click();
						layer.alert(feedback.msg);
					}
				});
			});

		})

	})
	var item = {};
    item.title='订单项';
    item.dataId='detail_id';
    item.deleteUrl='#(path)/portal/form/business/delete?object=sys_tree&primaryKey='+item.dataId;
    item.updateUrl='#(path)/portal/form/business/edit?viewCode=view_update&id=';
    item.addUrl='#(path)/erp/order/purchaseDetail/add';
    item.gridDivId ='maingrid';
    initGrid({id : 'maingrid'
        ,elem : '#maingrid'
        ,cellMinWidth: 80
        ,cols : [ [
            {title: '主键',field : 'detail_id',width : 35,checkbox : true},
            {title: '序号',type:'numbers',width:35},
            {title: '物品', field: 'entityName', event: 'setEntity',edit:'text' },
            {title: '所属上级', field: 'parEntityName'},
            {title: '计量单位', field: 'unit',edit:'text'},
            {title: '数量', field: 'amount',edit:'text'},
            {title: '价格', field: 'price',edit:'text'},
            {title: '折扣', field: 'discount',edit:'text'},
            {title: '金额', field: 'sum_money',edit:'text'},
            {title: '操作', field: 'tempId', fixed: 'right', width : 80, align : 'left',toolbar : '#bar_maingrid'} // 这里的toolbar值是模板元素的选择器

        ] ]
        ,data: []
        ,where:{"object":"sys_tree","primaryKey":item.dataId}
        ,searchForm : 'searchForm'
    },{
    	setEntity: setEntity,
    	delRow:delRow,
    	setPayCode:setPayCode,
    	delRow2:delRow2
    }, item);

	var args = {};
    args.title='付款明细';
    args.dataId='detail_id';
    args.deleteUrl='#(path)/portal/form/business/delete?object=sys_tree&primaryKey='+gridArgs.dataId;
    args.updateUrl='#(path)/portal/form/business/edit?viewCode=view_update&id=';
    args.addUrl='#(path)/erp/order/purchaseDetail/add';
    args.gridDivId ='payDetail';
    initGrid({id : 'payDetail'
        ,elem : '#payDetail'
        ,cellMinWidth: 80
        ,cols : [ [
            {title: '主键',field : 'detail_id',width : 35,checkbox : true},
            {title: '序号',type:'numbers',width:35},
            {title: '支付编码', field: 'pay_code', event: 'setPayCode'},
            {title: '支付金额', field: 'sum_money',edit:'text'},
            {title: '支付方', field: 'pay_men',edit:'text'},
            {title: '收入方', field: 'receive_men',edit:'text'},
            {title: '交易时间', field: 'trans_time',edit:'text'},
            {title: '操作', field: 'tempId', fixed: 'right', width : 80, align : 'left',toolbar : '#bar_payDetail'} // 这里的toolbar值是模板元素的选择器

        ] ]
        ,data:[]
        ,where:{"object":"sys_tree","primaryKey":gridArgs.dataId}
        ,searchForm : 'searchForm'
    },{
    	setPayCode:setPayCode,
    	delRow2:delRow2
    }, args);

	function setEntity(obj){
		var entityId ; var entityName;
		var par_entity; var par_entity_id;
		openDialogReturn("物品树形展示窗口","#(path)/erp/info/entity/renderEntityTree",false,null,null,null,function(res){
             entityId = res.entityId;
             entityName = res.entityName;

            // 后台发起请求，查询父级物品信息
            $.ajax({
                type: 'post',
                url: '#(path)/erp/info/entity/getParent',
                data: {
                    entityId:entityId
                },
                async: false,
                dataType: 'json',
                success: function (result) {
                    par_entity = result.entity_name;	// 修改表格值
                    par_entity_id = result.entity_id;	// 修改表格值

                }
            });
            var oldData = table.cache['maingrid'];
            for(var i=0, row; i < oldData.length; i++){
				row = oldData[i];
				if(row.tempId == obj.data.tempId){
					debugger;
					row.entity_id = entityId;
					row.entityName = entityName;
					row.parEntityName = par_entity;
					row.par_entity = par_entity_id;

				}
				continue;
			}
			table.reload('maingrid',{
				data : oldData
			});
        });

	}

	function setPayCode(obj){
		debugger
		var payCode ,account,payType
		openDialogReturn("支付方式选择窗口","#(path)/erp/info/payment/index",false,null,null,null,function(res){
             payCode = res.payCode;
			 account = res.account;
			 payType = res.payType;
            var oldData = table.cache['payDetail'];
            for(var i=0, row; i < oldData.length; i++){
				row = oldData[i];
				if(row.tempId == obj.data.tempId){
					debugger;
					row.pay_code = payCode;
					row.account = account;
					row.payType = payType;
				}
				continue;
			}
			table.reload('payDetail',{
				data : oldData
			});
        });

	}

	function delRow(obj){
		obj.del(); // 删除当前行
		var oldData = table.cache['maingrid'];
		for(var i=0, row; i < oldData.length; i++){
			row = oldData[i];
			if(!row || !row.tempId){
				oldData.splice(i, 1);    //删除一项
			}
			continue;
		}
		table.reload('maingrid',{
				data : oldData
		});
	}
	function delRow2(obj){
		debugger
		obj.del(); // 删除当前行
		var oldData = table.cache['payDetail'];
		for(var i=0, row; i < oldData.length; i++){
			row = oldData[i];
			if(!row || !row.tempId){
				oldData.splice(i, 1);    //删除一项
			}
			continue;
		}
		table.reload('payDetail',{
				data : oldData
		});
	}

</script>

#end

<!-- 时间控件 -->
#define layuiFunc()

	//监听单元格编辑
    table.on('edit(maingrid)', function(obj){
        var value = obj.value //得到修改后的值
            ,data = obj.data //得到所在行所有键值
            ,field = obj.field; //得到字段
		obj.update(field) //修改当前行数据

    });

	//监听单元格编辑
    table.on('edit(payDetail)', function(obj){
        var value = obj.value //得到修改后的值
            ,data = obj.data //得到所在行所有键值
            ,field = obj.field; //得到字段
		obj.update(field) //修改当前行数据

    });

	// 供应商输入框点击事件
    $("#supplierName").on('click',function () {
        openDialogReturn("供应商选择窗口","#(path)/erp/info/supplier/index",false,null,null,null,function (res) {
            var supplierId = res.supplierId;
            var supplierName = res.supplierName;
            $("#supplierId").val(supplierId);
            $("#supplierName").val(supplierName);
        });
    })
	// 起单人输入框点击事件
    $("#originatorName").on('click',function () {
        openDialogReturn("开单人选择窗口","#(path)/portal/core/sysUser/index",false,null,null,null,function (res) {
            var userCode = res.userCode;
            var userName = res.userName;
            $("#originator").val(userCode);
            $("#originatorName").val(userName);
        });
    })

    laydate.render({
        elem: '#originatTime',
        type: 'datetime'
    });
    laydate.render({
        elem: '#planTime',
        type: 'datetime'
    });
    laydate.render({
        elem: '#actualTime',
        type: 'datetime'
    });
#end

